package com.mall.order.services;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.mall.commons.tool.exception.ValidateException;
import com.mall.order.OrderQueryService;
import com.mall.order.constant.OrderRetCode;
import com.mall.order.constants.OrderConstants;
import com.mall.order.converter.OrderConverter;
import com.mall.order.dal.entitys.*;
import com.mall.order.dal.persistence.OrderItemMapper;
import com.mall.order.dal.persistence.OrderMapper;
import com.mall.order.dal.persistence.OrderShippingMapper;
import com.mall.order.dto.*;
import com.mall.order.utils.ExceptionProcessorUtils;
import com.mall.user.dal.entitys.Member;
import com.mall.user.dal.persistence.MemberMapper;
import com.sun.org.apache.xml.internal.resolver.readers.ExtendedXMLCatalogReader;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.common.utils.CollectionUtils;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import tk.mybatis.mapper.entity.Example;

import java.util.ArrayList;
import java.util.List;

/**
 *  ciggar
 * create-date: 2019/7/30-上午10:04
 */
@Slf4j
@Service
public class OrderQueryServiceImpl implements OrderQueryService {

    @Autowired
    OrderItemMapper orderItemMapper;
    @Autowired
    OrderConverter orderConverter;
    @Autowired
    OrderShippingMapper orderShippingMapper;
    @Autowired
    OrderMapper orderMapper;

    @Autowired
    MemberMapper memberMapper;

    @Override
    public OneOrderDetailResponse getOneOrderDetail(OneOrderDetailRequest request) {
        OneOrderDetailResponse response = new OneOrderDetailResponse();
        String orderId = request.getOrderId();
        Example example = new Example(OrderItem.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("orderId",orderId);
        try {
            List<OrderItem> orderItems = orderItemMapper.selectByExample(example);
            List<OrderItemDto> orderItemDtos = orderConverter.item2dto(orderItems);
            response.setGoodsList(orderItemDtos);
            OrderShipping orderShipping = orderShippingMapper.selectByPrimaryKey(orderId);
            response.setTel(orderShipping.getReceiverPhone());
//            response.setStreetName(orderShipping.getReceiverCity()
//                    + orderShipping.getReceiverDistrict() + orderShipping.getReceiverAddress());
            response.setStreetName(orderShipping.getReceiverAddress());
            Order order = orderMapper.selectByPrimaryKey(orderId);
            response.setOrderStatus(order.getStatus());
            response.setOrderTotal(order.getPayment());
            response.setCode(OrderRetCode.SUCCESS.getCode());
            response.setMsg(OrderRetCode.SUCCESS.getMessage());
        } catch (Exception e) {
            log.error("OrderQueryServiceImpl.getOneOrderDetail Occur error " + e);
            response.setCode(OrderRetCode.DB_EXCEPTION.getCode());
            response.setMsg(OrderRetCode.DB_EXCEPTION.getMessage());
        }
        return response;
    }

    @Override
    public AllUserOrderResponse getUserAllOrder(AllUserOrderRequest request) {
        AllUserOrderResponse response = new AllUserOrderResponse();
        try{
            request.requestCheck();
        } catch (ValidateException e) {
            response.setCode(e.getErrorCode());
            response.setMsg(e.getMessage());
            return response;
        }
        PageHelper.startPage(request.getPage(), request.getSize());

        //根据username获得userid
        Long userId = getUserIdByUserName(request.getUsername());
        Example orderExample = new Example(Order.class);
        orderExample.createCriteria().andEqualTo("userId", userId);
        if (request.getSort() != null && !"".equals(request.getSort())) {
            orderExample.setOrderByClause("order_id desc");
        } else {
            orderExample.setOrderByClause("create_time desc");
        }

        List<Order> orders = orderMapper.selectByExample(orderExample);
        List<OrderDetailInfo> orderDetailInfos = orderConverter.order2detail(orders);
        for (OrderDetailInfo orderDetailInfo : orderDetailInfos) {
            List<OrderItemDto> orderItemDtos = getOrderItemDtos(orderDetailInfo);
            orderDetailInfo.setOrderItemDto(orderItemDtos);
            Example shipExample = new Example(OrderShipping.class);
            OrderShippingDto orderShippingDto = getOrderShippingDto(orderDetailInfo, shipExample);
            orderDetailInfo.setOrderShippingDto(orderShippingDto);
        }
        PageInfo pageInfo = new PageInfo(orders);

        response.setTotal(pageInfo.getTotal());
        response.setData(orderDetailInfos);
        response.setCode(OrderRetCode.SUCCESS.getCode());
        response.setMsg(OrderRetCode.SUCCESS.getMessage());
        return response;
    }


    private Long getUserIdByUserName(String username) {
        Example example = new Example(Member.class);
        example.createCriteria().andEqualTo("username", username);
        List<Member> members = memberMapper.selectByExample(example);
        return members.get(0).getId();
    }

    private OrderShippingDto getOrderShippingDto(OrderDetailInfo orderDetailInfo, Example shipExample) {
        shipExample.createCriteria().andEqualTo("orderId",orderDetailInfo.getOrderId());
        List<OrderShipping> orderShippings = orderShippingMapper.selectByExample(shipExample);
        return orderConverter.shipping2dto(orderShippings.get(0));
    }

    private List<OrderItemDto> getOrderItemDtos(OrderDetailInfo orderDetailInfo) {
        Example orderItemExample = new Example(OrderItem.class);
        orderItemExample.createCriteria().andEqualTo("orderId", orderDetailInfo.getOrderId());
        List<OrderItem> orderItems = orderItemMapper.selectByExample(orderItemExample);
        return orderConverter.item2dto(orderItems);
    }
}
